package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.PropertyUtil;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.WmsBoxMapper;
import com.jy.wms.dao.WmsOwnerMapper;
import com.jy.wms.dao.WmsReviewMapper;
import com.jy.wms.dao.WmsSetBoxMapper;
import com.jy.wms.pojo.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
    * @ClassName: WmsReviewService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author Jane
    * @Date Tue Jan 30 10:19:46 CST 2018
    */

    @Service
    public class WmsReviewService extends BaseService<WmsReviewMapper,WmsReview> {

        @Autowired
        private WmsSetBoxMapper wmsSetBoxMapper;

        @Autowired
        private WmsBoxMapper wmsBoxMapper;
        @Autowired
        private WmsOwnerMapper wmsOwnerMapper;

    @BaseServiceDescribe(moduleName = "出库复核",btnName = "出库复核异常处理扫码页面")
    public JSONObject getEdit(String xbh, HttpSession session)throws ServiceException {
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        Map<String,Object> map = wmsSetBoxMapper.getPrintByXbh(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
        WmsReview wmsReview = dao.getByXbh(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
        //判断如果是 集拼箱编号则查询信息 如果不是则判断是否存在于集拼箱，如果是则获取集拼箱信息 如果不是则获取箱信息
        if(map != null){
            JSONObject json = getXmx(xbh,session,false);
            json.put("fhid",wmsReview.getId());
            return json;
        }else{
            String jpxId = dao.getBoxByXbh(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));

            if(wmsReview != null && wmsReview.getFhzt().equals("2")){
                if(!jpxId.equals("0")){
                    WmsSetBox wmsSetBox = wmsSetBoxMapper.baseSelectByPrimaryKey(jpxId);
                    xbh = wmsSetBox.getXbh();
                }
            }else{
                throw new ServiceException("该箱没有产生复核失败信息");
            }
            //获取装箱列表信息 如果装箱列表查询到改箱号则进行判断是否散箱
            List<Map<String,Object>> zxList = dao.getZxmx(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
            List<Map<String,Object>> zxListZx = dao.getZxmxZx(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
            JSONObject json = new JSONObject();
            json.put("fhid",wmsReview.getId());
            json.put("sjzl",wmsReview.getSjzl());
            if(zxList.size()>0){
                if("0".equals(zxList.get(0).get("zslx").toString())){
                    throw new ServiceException("称重复核不包括整箱");
                }else{
                    Double zl = 0.0;
                    int i;
                    for( i = 0;i < zxList.size(); i++ ){
                        zl += Double.valueOf(zxList.get(i).get("zl").toString());
                    }
                    json.put("dydh",zxList.get(0).get("fydh").toString());
                    json.put("lxr",zxList.get(0).get("lxr").toString());
                    json.put("dz",zxList.get(0).get("dz").toString());
                    json.put("xx",zxList.get(0).get("xx").toString());
                    json.put("zl",zl);
                    json.put("zdzl",zl + Double.valueOf(zxList.get(0).get("zl").toString()));
                    json.put("zxzl",zl - Double.valueOf(zxList.get(0).get("zl").toString()));
                    json.put("rows",zxList);
                    json.put("total",zxList.size());
                    json.put("zxdwzl",zxListZx.get(0).get("zl").toString());
                    json.put("type",0);
                    //总重量
                    json.put("zzl",zl + Double.valueOf(zxListZx.get(0).get("zzxzl").toString()));
                    json.putAll(wmsSetBoxMapper.getBoxNumber(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0))));
                    return json;
                }
            }else{
                //集拼箱名称
                Map<String,Object> boxMap = wmsSetBoxMapper.getPrintByXbh(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
                if(boxMap != null && boxMap.size()>0){
                    json.putAll(boxMap);
                    json.put("fydh",wmsSetBoxMapper.getFydh(json.get("id").toString()));
                    WmsSetBox wmsSetBox = wmsSetBoxMapper.baseSelectByPrimaryKey(json.get("id").toString());
                    List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
                    if(hz.size()>0){
                        json.put("hzmc",hz.get(0).getShow_hzid());
                    }
                    json.put("ckmc",userinfo.getUser().getOrgName());
                    json.put("cklxr",userinfo.getOrgs().get(0).getMaster());
                    json.put("lxr",wmsSetBox.getLxr());
                    json.put("dz",wmsSetBox.getDz());
                    String host = PropertyUtil.getProperty("safety.host");
                    String port = PropertyUtil.getProperty("safety.port");
                    String result = HttpUtil.doGet("http://"+host+":"+port+"/ms-safety/org/getOrgInfo/"+ String.valueOf(userinfo.getUser().getOrgId().get(0)),session.getId());
                    json.put("ckdz", JSONObject.fromObject(result).get("address") == null?"":JSONObject.fromObject(result).get("address"));
                    json.put("kfrx",userinfo.getOrgs().get(0).getTelephone() == null?"":userinfo.getOrgs().get(0).getTelephone());
                    List<Map<String,Object>> list = wmsSetBoxMapper.getPrintList(json.get("id").toString());
                    Double zl = 0.0;
                    for( int i = 0;i < list.size(); i++ ){
                        zl += Double.valueOf(list.get(i).get("zl").toString());
                    }
                    List<Map<String,Object>> listZx = wmsSetBoxMapper.getPrintListZx(json.get("id").toString());
                    json.put("list",list);
                    json.put("zdzl", Double.valueOf(json.get("zl").toString()) + Double.valueOf(list.get(0).get("zl").toString()));
                    json.put("zxzl", Double.valueOf(json.get("zl").toString()) - Double.valueOf(list.get(0).get("zl").toString()));
                    json.put("zxdwzl", Double.valueOf(listZx.get(0).get("zl").toString()));
                    //总重量
                    json.put("zzl",zl + Double.valueOf(zxListZx.get(0).get("zzxzl").toString()));
                    json.put("type",1);
                    return json;
                }else{
                    throw new ServiceException("查询失败");
                }
            }
        }
    }

    /**
     *
     * @param xbh
     * @param session
     * @param type 扫码类型 true表示正常扫码  false表示异常处理扫码
     * @return
     * @throws ServiceException
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "出库复核扫码页面")
    public JSONObject getXmx(String xbh, HttpSession session, boolean type)throws ServiceException {
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        //判断该单是否已经复核过
        WmsReview wmsReview = dao.getByXbh(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
        List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
        WmsOwner wmsOwner = wmsOwnerMapper.baseSelectByPrimaryKey(hz.get(0).getHzid());
        if(wmsReview != null && type){
            if(wmsReview.getFhzt().equals("2")){
                throw new ServiceException("该单复核信息异常,请及时处理");
            }else {
                throw new ServiceException("此箱已复核完毕，不要重复操作");
            }
        } else if("0".equals(wmsOwner.getCkfh())){
            //如果货主出库复核为0 则无法进行出库复核
            throw new ServiceException("当前货主配置不允许进行出库复核");
        } else{
            //获取装箱列表信息 如果装箱列表查询到改箱号则进行判断是否散箱
            List<Map<String,Object>> zxList = dao.getZxmx(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
            List<Map<String,Object>> zxListZx = dao.getZxmxZx(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
            JSONObject json = new JSONObject();
            if(zxList.size()>0){
                if("0".equals(zxList.get(0).get("zslx").toString())){
                    throw new ServiceException("称重复核不包括整箱");
                }else{
                    Double zl = 0.0;
                    int i;
                    for( i = 0;i < zxList.size(); i++ ){
                        zl += Double.valueOf(zxList.get(i).get("zl").toString());
                    }
                    json.put("dydh",zxList.get(0).get("fydh").toString());
                    json.put("lxr",zxList.get(0).get("lxr").toString());
                    json.put("dz",zxList.get(0).get("dz").toString());
                    json.put("xx",zxList.get(0).get("xx").toString());
                    json.put("zl",zl);
                    //最大重量
                    json.put("zdzl",zl + Double.valueOf(zxList.get(0).get("zl").toString()));
                    //最小重量
                    json.put("zxzl",zl - Double.valueOf(zxList.get(0).get("zl").toString()));
                    //最小单位重量
                    json.put("zxdwzl", Double.valueOf(zxList.get(0).get("zl").toString()));
                    //总重量
                    json.put("zzl",zl + Double.valueOf(zxList.get(0).get("zzxzl").toString()));
                    json.put("contentList",zxList);
                    json.put("totals",zxList.size());

                    json.put("type",0);
                    json.putAll(wmsSetBoxMapper.getBoxNumber(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0))));
                    return json;
                }
            }else{
                //集拼箱名称
                Map<String,Object> boxMap = wmsSetBoxMapper.getPrintByXbh(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
                if(boxMap != null && boxMap.size()>0){
                    json.putAll(boxMap);
                    json.put("fydh",wmsSetBoxMapper.getFydh(json.get("id").toString()));
                    WmsSetBox wmsSetBox = wmsSetBoxMapper.baseSelectByPrimaryKey(json.get("id").toString());
                    if(hz.size()>0){
                        json.put("hzmc",hz.get(0).getShow_hzid());
                    }
                    json.put("ckmc",userinfo.getUser().getOrgName());
                    json.put("cklxr",userinfo.getOrgs().get(0).getMaster());
                    json.put("lxr",wmsSetBox.getLxr());
                    json.put("dz",wmsSetBox.getDz());
                    String host = PropertyUtil.getProperty("safety.host");
                    String port = PropertyUtil.getProperty("safety.port");
                    String result = HttpUtil.doGet("http://"+host+":"+port+"/ms-safety/org/getOrgInfo/"+ String.valueOf(userinfo.getUser().getOrgId().get(0)),session.getId());
                    json.put("ckdz", JSONObject.fromObject(result).get("address") == null?"":JSONObject.fromObject(result).get("address"));
                    json.put("kfrx",userinfo.getOrgs().get(0).getTelephone() == null?"":userinfo.getOrgs().get(0).getTelephone());
                    List<Map<String,Object>> list = wmsSetBoxMapper.getPrintList(json.get("id").toString());
                    Double zl = 0.0;
                    for( int i = 0;i < list.size(); i++ ){
                        zl += Double.valueOf(list.get(i).get("zl").toString());
                    }
                    List<Map<String,Object>> listZx = wmsSetBoxMapper.getPrintListZx(json.get("id").toString());
                    json.put("list",list);
                    json.put("zdzl", Double.valueOf(json.get("zl").toString()) + Double.valueOf(listZx.get(0).get("zl").toString()));
                    json.put("zxzl", Double.valueOf(json.get("zl").toString()) - Double.valueOf(listZx.get(0).get("zl").toString()));
                    json.put("zxdwzl", Double.valueOf(list.get(0).get("zl").toString()));
                    //总重量
                    json.put("zzl",zl + Double.valueOf(list.get(0).get("zzxzl").toString()));
                    json.put("type",1);
                    return json;
                }else{
                    throw new ServiceException("查询失败");
                }

            }
        }
    }

     /**
     * 插入一条记录
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsert(WmsReview entity){
         return dao.baseInsert( entity );
    }

    /**
     * 插入一条记录（匹配有值的字段）
     * @param xbh 实体对象
     * @return int
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "修改复核状态为成功")
    @Transactional
    public void fhcg(String xbh, BigDecimal sjzl) throws ServiceException,SucessException {
        try {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("fhzt","1");
            //获取箱IDs
            List<String> ids = wmsBoxMapper.baseSelectByPrimaryXbh(xbh);
            //获取集拼箱IDS
            List<String> jpxIds = dao.baseSelectByPrimaryXbh(xbh);
            //Map<String,Object> value = new HashMap<String,Object>();
            Map<String,Object> values = new HashMap<String,Object>();
            //如果装箱信息存在 修改实际重量
            if(ids.size() > 0) {
                /*value.put("list",ids);
                value.put("sjzl",sjzl);*/
                for(String id:ids){
                    values.put("id",id);
                    values.put("sjzl",sjzl);
                    dao.boxUpdates(values);
                }
                //dao.boxUpdate(value);
            }
            //如果集拼箱信息存在 根据集拼箱ID修改实际重量
            if(jpxIds.size() > 0){
                /*value.put("list",jpxIds);
                value.put("sjzl",sjzl);*/
                for(String id:jpxIds){
                    values.put("id",id);
                    values.put("sjzl",sjzl);
                    dao.boxUpdateByJpxids(values);
                }
                //dao.boxUpdateByJpxid(value);
            }
            List<String> list=new ArrayList<>();
            list=ids.size() > 0 ? ids : jpxIds;
            //map.put("list",ids.size() > 0 ? ids : jpxIds);
            for(String id:list){
                map.put("id",id);
                dao.updatePickingFhzts(map);
            }
            //dao.updatePickingFhzt(map);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

   /**
    * 插入一条记录（匹配有值的字段）
    * @param list 实体对象
    * @return int
    */
   @BaseServiceDescribe(moduleName = "出库复核",btnName = "新增出库复核")
   @Transactional
    public void baseInsertSelective(List<WmsReview> list, HttpSession session ) throws ServiceException,SucessException {
       List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
       WmsOwner wmsOwner = wmsOwnerMapper.baseSelectByPrimaryKey(hz.get(0).getHzid());
       if("0".equals(wmsOwner.getCkfh())){
           throw new ServiceException("当前货主配置不允许进行出库复核");
       }else{
           //如果该箱已经在复核表内存在则全单不允许加入
           UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
           Boolean type = true;
           StringBuffer msg = new StringBuffer();
           for (WmsReview entity : list) {
               entity.setId(UUIDUtils.uuid());
               SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
               entity.setFhsj(formatter.format(new Date()));
               entity.setCkid(String.valueOf(userinfo.getUser().getOrgId().get(0)));
               Integer count = dao.getCountByXbh(entity.getXbh(), String.valueOf(userinfo.getUser().getOrgId().get(0)));
               if(count > 0 ){
                   type = false;
                   msg.append(entity.getXbh());
                   msg.append(",");
               }
           }
           if(type){
               for (WmsReview entity : list) {
                   Map<String,Object> map = new HashMap<String,Object>();
                   map.put("fhzt",entity.getFhzt().toString());
                   List<String> ids = wmsBoxMapper.baseSelectByPrimaryXbh(entity.getXbh());
                   List<String> jpxIds = dao.baseSelectByPrimaryXbh(entity.getXbh());
                   Map<String,Object> value = new HashMap<String,Object>();
                   //如果装箱信息存在 修改实际重量
                   if(ids.size() > 0) {
                       value.put("list",ids);
                       value.put("sjzl",entity.getSjzl());
                       dao.boxUpdate(value);
                   }
                   //如果集拼箱信息存在 根据集拼箱ID修改实际重量
                   if(jpxIds.size() > 0){
                       value.put("list",jpxIds);
                       value.put("sjzl",entity.getSjzl());
                       dao.boxUpdateByJpxid(value);
                   }
                   map.put("list",ids.size() > 0 ? ids : jpxIds);
                   dao.updatePickingFhzt(map);
               }
               dao.baseInsertAll(list);
               throw new SucessException("新增出库复核成功");
           }else{
               msg.append("箱编号已复核");
               throw new ServiceException(msg.toString());
           }
       }
   }

   /**
    * 删除（根据主键ID删除）
    * @param id 主键
    * @return int
    */
    public Integer baseDeleteByPrimaryKey(String id){
         return dao.baseDeleteByPrimaryKey( id);
    }

   /**
    * 删除（根据ID 批量删除）
    * @param idList 主键ID列表
    * @return int
    */
    public Integer baseDeleteBathPrimaryKeys(List<String> idList){
         return dao.baseDeleteBathPrimaryKeys( idList );
    }

    /**
     * 根据发运订单批量打印整箱标签
     * @param ids 发运订单ID
     * @return
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "根据箱批量打印快递面单")
    public Map<String,Object> zxPrintByXids(List<String> ids) throws Exception {
        //查询所有 发运订单对应的箱信息
        //快递100返回信息
        JSONObject reJson = new JSONObject();
        //承接返回快递面单网址LIST
        List<String> getList = new ArrayList<String>();
        StringBuffer message = new StringBuffer();
        List<Map<String,Object>> list = dao.zxPrintByXids(ids);
        for (Map<String, Object> stringObjectMap : list) {
            if(stringObjectMap.get("zslx").toString().equals("0")){
                if(stringObjectMap.get("cyslb").toString().equals("3")||stringObjectMap.get("cyslb").toString().equals("6")){//申通或圆通
                    reJson =  ExpressSurfaceBill.print(stringObjectMap);
                    if(!(reJson.get("status").toString().equals("200"))){
                        message.append("发运单号" + stringObjectMap.get("fybh").toString() + ",箱编号" + stringObjectMap.get("xbh").toString() + reJson.get("message").toString());
                    }else {
                        //修改装箱表的打印次数\
                        Integer num=(Integer)stringObjectMap.get("num")+1;
                        int a= dao.updateNum(num,stringObjectMap.get("xbh").toString());

                        JSONArray jsonArray = JSONArray.fromObject(reJson.get("data").toString());
                        JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(0));
                        WmsAssistDelivery wmsAssistDelivery = new WmsAssistDelivery();
                        wmsAssistDelivery.setSf(stringObjectMap.get("sheng").toString());
                        wmsAssistDelivery.setCs(stringObjectMap.get("shi").toString());
                        Map<String, Object> messageMap = new HashMap<>();
                        //计算运费
                        Integer yf =0;
                        if(stringObjectMap.get("cyslb").toString().equals("3")){//申通
                             yf = new HttpUtil().computationalCosts(wmsAssistDelivery, Double.valueOf(stringObjectMap.get("zl").toString().toString()));
                            //发运公司
                            messageMap.put("ysgs", ckfhInfo.fydd_dx_kdgs.getType());
                        }else if(stringObjectMap.get("cyslb").toString().equals("6")) {//圆通
                             yf = new HttpUtil().ytComputationalCosts(wmsAssistDelivery, Double.valueOf(stringObjectMap.get("zl").toString().toString()));
                            //发运公司
                            messageMap.put("ysgs", ckfhInfo.fydd_dx_kdgs2.getType());
                        }

                        //快递单号
                        messageMap.put("ysdh", jsonObject.get("kuaidinum").toString());
                        messageMap.put("lxrxm", stringObjectMap.get("lxr").toString());
                        messageMap.put("lxrdh", stringObjectMap.get("lxrdh").toString());
                        messageMap.put("yf", yf);
                        //判断是否集拼箱
                        Set<String> fyddids;
                        if (stringObjectMap.get("xbh").toString().substring(0, 3).equals("JPX")) {
                            //如果是集拼箱查找所有装箱信息
                            WmsSetBox wmsSetBox = wmsSetBoxMapper.baseSelectByPrimaryXbh(stringObjectMap.get("xbh").toString());
                            messageMap.put("jpxid", wmsSetBox.getId());
                            //写入快递信息
                            wmsSetBoxMapper.updateBoxMessageByJpxid(messageMap);
                            //获取发运订单列表
                            fyddids = wmsSetBoxMapper.getFyddIdsByJpxId(wmsSetBox.getId());
                        } else {
                            //如果是装箱则查询装箱
                            messageMap.put("xbh", stringObjectMap.get("xbh").toString());
                            wmsSetBoxMapper.updateBoxMessageByZxid(messageMap);
                            //获取发运订单列表
                            fyddids = wmsSetBoxMapper.getFyddIdsByXbh(stringObjectMap.get("xbh").toString());
                        }
                        //修改发运订单运费
                        for (String fyddid : fyddids) {
                            WmsShipmentOrder so=new WmsShipmentOrder();
                            so.setId(fyddid);
                            so.setZyf(wmsBoxMapper.sumYf(fyddid).toString());
                            wmsBoxMapper.updateSoYf(so);
                        }
                        getList.add(JSONObject.fromObject(JSONArray.fromObject(reJson.get("data").toString()).get(0)).get("templateurl").toString());
                    }
                }else{
                    message.append("发运单号" + stringObjectMap.get("fybh").toString() + ",箱编号" + stringObjectMap.get("xbh").toString() + "承运商类别为" + stringObjectMap.get("show_cyslb").toString() + ",");
                }
            }else{
                message.append("发运单号" + stringObjectMap.get("fybh").toString() + ",箱编号" + stringObjectMap.get("xbh").toString() + "是散箱,");
            }
        }
        Map<String,Object> messageMap = new HashMap<String,Object>();
        if(message.length() > 0){
            messageMap.put("dz",JSONArray.fromObject(getList));
            messageMap.put("message",message.toString());
        }else{
            messageMap.put("dz",JSONArray.fromObject(getList));
            messageMap.put("message","");
        }
        return messageMap;
    }

    /**
     * 根据发运订单批量打印整箱标签
     * @param ids 发运订单ID
     * @return
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "根据发运订单批量打印快递面单")
    public Map<String,Object> zxPrintByFyIds(List<String> ids) throws Exception {
        //查询所有 发运订单对应的箱信息
        //快递100返回信息
        JSONObject reJson = new JSONObject();
        //承接返回快递面单网址LIST
        List<String> getList = new ArrayList<String>();
        StringBuffer message = new StringBuffer();
        List<Map<String,Object>> list = dao.zxPrintByFyIds(ids);
        for (Map<String, Object> stringObjectMap : list) {
            if(stringObjectMap.get("zslx").toString().equals("0")){
                if(stringObjectMap.get("cyslb").toString().equals("3")||stringObjectMap.get("cyslb").toString().equals("6")){//申通或圆通

                    reJson =  ExpressSurfaceBill.print(stringObjectMap);
                    if(!(reJson.get("status").toString().equals("200"))){
                        message.append("发运单号" + stringObjectMap.get("fybh").toString() + ",箱编号" + stringObjectMap.get("xbh").toString() + reJson.get("message").toString());
                    }else {
                        //修改装箱表的打印次数\

                        Integer num=(Integer)stringObjectMap.get("num")+1;
                        int a= dao.updateNum(num,stringObjectMap.get("xbh").toString());

                        JSONArray jsonArray = JSONArray.fromObject(reJson.get("data").toString());
                        JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(0));
                        WmsAssistDelivery wmsAssistDelivery = new WmsAssistDelivery();
                        wmsAssistDelivery.setSf(stringObjectMap.get("sheng").toString());
                        wmsAssistDelivery.setCs(stringObjectMap.get("shi").toString());
                        Map<String, Object> messageMap = new HashMap<>();
                        //计算运费
                        Integer yf=0;
                        if(stringObjectMap.get("cyslb").toString().equals("3")){//申通
                            yf = new HttpUtil().computationalCosts(wmsAssistDelivery, Double.valueOf(stringObjectMap.get("zl").toString().toString()));
                            //发运公司
                            messageMap.put("ysgs", ckfhInfo.fydd_dx_kdgs.getType());
                        }else if(stringObjectMap.get("cyslb").toString().equals("6")) {//圆通
                            yf = new HttpUtil().ytComputationalCosts(wmsAssistDelivery, Double.valueOf(stringObjectMap.get("zl").toString().toString()));
                            //发运公司
                            messageMap.put("ysgs", ckfhInfo.fydd_dx_kdgs2.getType());
                        }

                        //快递单号
                        messageMap.put("ysdh", jsonObject.get("kuaidinum").toString());
                        messageMap.put("lxrxm", stringObjectMap.get("lxr").toString());
                        messageMap.put("lxrdh", stringObjectMap.get("lxrdh").toString());
                        messageMap.put("yf", yf);
                        //判断是否集拼箱
                        Set<String> fyddids;
                        if (stringObjectMap.get("xbh").toString().substring(0, 3).equals("JPX")) {
                            //如果是集拼箱查找所有装箱信息
                            WmsSetBox wmsSetBox = wmsSetBoxMapper.baseSelectByPrimaryXbh(stringObjectMap.get("xbh").toString());
                            messageMap.put("jpxid", wmsSetBox.getId());
                            //写入快递信息
                            wmsSetBoxMapper.updateBoxMessageByJpxid(messageMap);
                            //获取发运订单列表
                            fyddids = wmsSetBoxMapper.getFyddIdsByJpxId(wmsSetBox.getId());
                        } else {
                            //如果是装箱则查询装箱
                            messageMap.put("xbh", stringObjectMap.get("xbh").toString());
                            wmsSetBoxMapper.updateBoxMessageByZxid(messageMap);
                            //获取发运订单列表
                            fyddids = wmsSetBoxMapper.getFyddIdsByXbh(stringObjectMap.get("xbh").toString());
                        }
                        //修改发运订单运费
                        for (String fyddid : fyddids) {
                            WmsShipmentOrder so=new WmsShipmentOrder();
                            so.setId(fyddid);
                            so.setZyf(wmsBoxMapper.sumYf(fyddid).toString());
                            wmsBoxMapper.updateSoYf(so);
                        }
                        getList.add(JSONObject.fromObject(JSONArray.fromObject(reJson.get("data").toString()).get(0)).get("templateurl").toString());
                    }

                }else{
                    message.append("发运单号" + stringObjectMap.get("fybh").toString() + ",箱编号" + stringObjectMap.get("xbh").toString() + "承运商类别为" + stringObjectMap.get("show_cyslb").toString() + ",");
                }
            }else{
                message.append("发运单号" + stringObjectMap.get("fybh").toString() + ",箱编号" + stringObjectMap.get("xbh").toString() + "是散箱,");
            }
        }
        Map<String,Object> messageMap = new HashMap<String,Object>();
        if(message.length() > 0){
            messageMap.put("dz",JSONArray.fromObject(getList));
            messageMap.put("message",message.toString());
        }else{
            messageMap.put("dz",JSONArray.fromObject(getList));
            messageMap.put("message","");
        }
        return messageMap;
    }


    /**
     * 根据发运订单批量打印整箱标签
     * @param ids 发运订单ID
     * @return
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "根据发运订单批量打印快递面单次数")
    public boolean getPrintNum(List<String> ids) throws Exception {

        List<Map<String,Object>> list = dao.zxPrintByFyIds(ids);
        boolean flag=true;
        for(Map map:list){
          if((Integer)map.get("num")>=1){
              flag=false;
              break;
          }
        }
         return flag;
    }

    /**
     * 分页查询
     * @param xbh 箱编号
     * @return
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "获取箱信息")
    public JSONObject getXxx(String xbh, HttpSession session) throws Exception {
        return JSONObject.fromObject(dao.getXxx(xbh));
    }

    /**
     * 分页查询
     * @param xbh 箱编号
     * @return
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "取消拆单")
    @Transactional
    public void cancel(String xbh, HttpSession session) throws SucessException,ServiceException {
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        WmsReview wmsReview = dao.getByXbh(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
        if(wmsReview != null){
            // 1、删除出库复核信息
            dao.baseDeleteByPrimaryKey(wmsReview.getId());
            // 2、更新 wms_picking 表内的fhzt 为 0
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("fhzt","0");
            List<String> ids = wmsBoxMapper.baseSelectByPrimaryXbh(xbh);
            List<String> jpxIds = dao.baseSelectByPrimaryXbh(xbh);
            Map<String,Object> value = new HashMap<String,Object>();
            map.put("list",ids.size() > 0 ? ids : jpxIds);
            dao.updatePickingFhzt(map);
            throw new SucessException();
        }else{
            throw new ServiceException("此复核信息不存在");
        }
    }

    /**
     * 分页查询
     * @param map 实际重量 width 箱编号 xbh
     * @return Page<WmsReview>
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "打印快递面单")
    public String print(Map<String,Object> map , HttpSession session) throws ServiceException {
        JSONObject json = new JSONObject();
        JSONObject sendMan = new JSONObject();
        String message = "";
        String xbh = map.get("xbh").toString();
        //获取箱信息
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        //判断货主是否有权限打印快递面单
        List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
        WmsOwner wmsOwner = wmsOwnerMapper.baseSelectByPrimaryKey(hz.get(0).getHzid());
        if("0".equals(wmsOwner.getFhdymd())){
            throw new ServiceException("当前货主配置不允许进行快递面单打印");
        }
        //判断该单是否已经复核过
        WmsReview wmsReview = dao.getByXbh(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
        if(wmsReview != null){
            if(wmsReview.getFhzt().equals("2")){
                throw new ServiceException("该单复核信息异常,请及时处理");
            }
        }
        String lxr;
        String lxrdh;
        String sheng;
        String shi;
        String dz;
        Double zl = 0.0;//重量
        Double sl = 0.0;//数量
        Double sjzl=0.0;//实际重量
        //分别获取装箱和集拼箱列表信息根据长度判断扫码属于哪一类
        List<Map<String,Object>> zxList = dao.getZxmx(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
        List<Map<String,Object>> jpxList = dao.getJpxMx(xbh, String.valueOf(userinfo.getUser().getOrgId().get(0)));
        Set<String> goodsIds = new HashSet<>();
        Map<String,Object> cyslb =null;
        if(zxList.size()>0){
          cyslb = dao.getCyslbByZx(xbh);
            //查询发运订单的承运商类别，如果是 1.快递 则打印面单 如果是其他则不打印
            if(!(cyslb.get("cyslb").toString().equals("3"))&&!(cyslb.get("cyslb").toString().equals("6"))){//不是申通或圆通时
                if(cyslb.get("cyslb").toString().equals("5")){
                    throw new ServiceException("该订单采用自提方式，无需打印快递面单");
                }
                throw new ServiceException("该订单采用 "+ cyslb.get("show_cyslb").toString() +"，是否维护快递信息");
            }
            lxr = zxList.get(0).get("lxr").toString();
            lxrdh = zxList.get(0).get("lxrdh").toString();
            sheng = zxList.get(0).get("sheng").toString();
            shi = zxList.get(0).get("shi").toString();
            dz = zxList.get(0).get("dz").toString();
            for (Map<String, Object> stringObjectMap : zxList) {
                zl += Double.valueOf(stringObjectMap.get("zl").toString());
                sl += Double.valueOf(stringObjectMap.get("sl").toString());
                sjzl= Double.valueOf(stringObjectMap.get("sjzl").toString());
                goodsIds.add(stringObjectMap.get("goodid").toString());
            }
            if(cyslb.get("cyslb").toString().equals("3")){//申通
                json.put("kuaidicom", ckfhInfo.ckfh_kuaidicom.getType());
                json.put("partnerId", ckfhInfo.ckfh_partnerId.getType());
                json.put("net", ckfhInfo.ckfh_net.getType());
                json.put("partnerKey", ckfhInfo.ckfh_partnerKey.getType());
                sendMan.put("mobile", ckfhInfo.ckfh_sendMan_mobile_st.getType());
            }else if(cyslb.get("cyslb").toString().equals("6")){//圆通
                json.put("kuaidicom", ckfhInfo.ckfh_kuaidicom2.getType());
                json.put("partnerId", ckfhInfo.ckfh_partnerId2.getType());
                json.put("net", ckfhInfo.ckfh_net2.getType());
                json.put("partnerKey", ckfhInfo.ckfh_partnerKey2.getType());
                sendMan.put("mobile", ckfhInfo.ckfh_sendMan_mobile_yt.getType());
            }

        }else if (jpxList.size() > 0){
            String cys=dao.getCyslbByJpx(xbh);
            if(!(cys.equals("3"))&&!(cys.equals("6"))){//不是申通或圆通时
                if(cys.equals("5")){
                    throw new ServiceException("该订单采用自提方式，无需打印快递面单");
                }
                //throw new ServiceException("该订单采用 "+ cyslb.get("show_cyslb").toString() +"，是否维护快递信息");
            }

            if(cys.equals("3")){//申通
                json.put("kuaidicom", ckfhInfo.ckfh_kuaidicom.getType());
                json.put("partnerId", ckfhInfo.ckfh_partnerId.getType());
                json.put("net", ckfhInfo.ckfh_net.getType());
                json.put("partnerKey", ckfhInfo.ckfh_partnerKey.getType());
                sendMan.put("mobile", ckfhInfo.ckfh_sendMan_mobile_st.getType());
            }else if(cys.equals("6")){//圆通
                json.put("kuaidicom", ckfhInfo.ckfh_kuaidicom2.getType());
                json.put("partnerId", ckfhInfo.ckfh_partnerId2.getType());
                json.put("net", ckfhInfo.ckfh_net2.getType());
                json.put("partnerKey", ckfhInfo.ckfh_partnerKey2.getType());
                sendMan.put("mobile", ckfhInfo.ckfh_sendMan_mobile_yt.getType());
            }

            /*if(!(dao.getCyslbByJpx(xbh).equals("1"))){
                throw new ServiceException("该单承运商类别没有选择快递，无需打印快递面单");
            }*/
            lxr = jpxList.get(0).get("lxr").toString();
            lxrdh = jpxList.get(0).get("lxrdh").toString();
            sheng = jpxList.get(0).get("sheng").toString();
            shi = jpxList.get(0).get("shi").toString();
            dz = jpxList.get(0).get("dz").toString();
            for (Map<String, Object> stringObjectMap : jpxList) {
                zl += Double.valueOf(stringObjectMap.get("zl").toString());
                sl += Double.valueOf(stringObjectMap.get("sl").toString());
                sjzl= Double.valueOf(stringObjectMap.get("sjzl").toString());
                goodsIds.add(stringObjectMap.get("goodid").toString());
             }
        } else {
            throw new ServiceException("扫码失败，请检查箱编号");
        }
        String goodsTypes = dao.getGoodsType(goodsIds);
        if(goodsTypes.length() > 48){
            goodsTypes = goodsTypes.substring(0,47) + "……";
        }

//        json.put("partnerId",ckfhInfo.ckfh_partnerId.getType());
//        json.put("net", ckfhInfo.ckfh_net.getType());
//        json.put("partnerKey", ckfhInfo.ckfh_partnerKey.getType());
        //json.put("kuaidicom", ckfhInfo.ckfh_kuaidicom.getType());
        json.put("orderId", "");

        sendMan.put("name", ckfhInfo.ckfh_sendMan_name.getType());
        sendMan.put("tel", ckfhInfo.ckfh_sendMan_tel.getType());
        sendMan.put("province", ckfhInfo.ckfh_sendMan_province.getType());
        sendMan.put("city", ckfhInfo.ckfh_sendMan_city.getType());
        sendMan.put("district", ckfhInfo.ckfh_sendMan_district.getType());
        sendMan.put("addr", ckfhInfo.ckfh_sendMan_addr.getType());
        sendMan.put("printAddr", ckfhInfo.ckfh_sendMan_printAddr.getType());
        sendMan.put("company", ckfhInfo.ckfh_sendMan_company.getType());
        json.put("sendMan", sendMan);
        JSONObject recMan = new JSONObject();
        recMan.put("name", lxr);
        recMan.put("mobile", lxrdh);
        recMan.put("province", sheng);
        recMan.put("city", shi);
        recMan.put("district", "");
        recMan.put("addr", "");
        recMan.put("printAddr", dz);
        recMan.put("company", "");
        json.put("recMan", recMan);
        json.put("cargo", goodsTypes);
        json.put("count", sl);
        json.put("weight", map.get("width").toString());
        json.put("volumn", zl);
        json.put("payType", "");
        json.put("expType", ckfhInfo.ckfh_expType.getType());
        json.put("remark", "");
        json.put("valinsPay", new Double(0));
        json.put("collection", new Double(0));
        json.put("needChild", ckfhInfo.ckfh_needChild.getType());
        json.put("needBack", ckfhInfo.ckfh_needBack.getType());
        json.put("needTemplate", ckfhInfo.ckfh_needTemplate.getType());
        Long t = System.currentTimeMillis();
        String key = ckfhInfo.ckfh_key.getType();
        String secret = ckfhInfo.ckfh_secret.getType();
        Map<String, Object> params = new HashMap<String, Object>();
        String sign = MD5.encode(json.toString() + t + key + secret);
        params.put("method", "getElecOrder");
        params.put("param", json.toString());
        params.put("sign", sign);
        params.put("t", t.toString());
        params.put("key", key);
        logger.info("原文：" + params.toString());
        String postData = "method=getElecOrder&param="+json.toString()+"&sign="+sign+"&t="+t+"&key="+key;
        logger.info("postData:" + postData);
        json = JSONObject.fromObject(Send.SMS(postData,"http://api.kuaidi100.com/eorderapi.do"));

        if(!(json.get("status").toString().equals("200"))){
            throw new ServiceException(json.get("message").toString());
        }else{
            //修改装箱表的打印次数\
            /*List<WmsBox> boxs=dao.getBox(xbh);
            for(WmsBox b:boxs){
                Integer num=b.getNum()+1;
                int a= dao.updateNum(num,b.getId());
            }*/
            List<WmsBox> boxs=dao.getBox(xbh);
            Integer num=boxs.get(0).getNum()+1;
            int a= dao.updateNum(num,xbh);


            JSONArray jsonArray = JSONArray.fromObject(json.get("data").toString());
            JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(0));
            WmsAssistDelivery wmsAssistDelivery = new WmsAssistDelivery();
            wmsAssistDelivery.setSf(sheng);
            wmsAssistDelivery.setCs(shi);
            Map<String,Object> messageMap = new HashMap<>();
            //计算运费
            Integer yf=0;
            if(cyslb.get("cyslb").toString().equals("3")){//申通
                yf = new HttpUtil().computationalCosts(wmsAssistDelivery, sjzl);
                //发运公司
                messageMap.put("ysgs", ckfhInfo.fydd_dx_kdgs.getType());
            }else if(cyslb.get("cyslb").toString().equals("6")) {//圆通
                yf = new HttpUtil().ytComputationalCosts(wmsAssistDelivery,sjzl);
                //发运公司
                messageMap.put("ysgs", ckfhInfo.fydd_dx_kdgs2.getType());
            }

            //发运公司
           // messageMap.put("ysgs",ckfhInfo.fydd_dx_kdgs.getType());

            //快递单号
            messageMap.put("ysdh",jsonObject.get("kuaidinum").toString());
            messageMap.put("lxrxm",lxr);
            messageMap.put("lxrdh",lxrdh);
            messageMap.put("yf",yf);
            //判断是否集拼箱
            Set<String> fyddids;
            if(xbh.substring(0,3).equals("JPX")){
                //如果是集拼箱查找所有装箱信息
                WmsSetBox wmsSetBox = wmsSetBoxMapper.baseSelectByPrimaryXbh(xbh);
                messageMap.put("jpxid",wmsSetBox.getId());
                //写入快递信息
                wmsSetBoxMapper.updateBoxMessageByJpxid(messageMap);
                //获取发运订单列表
                fyddids = wmsSetBoxMapper.getFyddIdsByJpxId(wmsSetBox.getId());
            } else {
                //如果是装箱则查询装箱
                messageMap.put("xbh",xbh);
                wmsSetBoxMapper.updateBoxMessageByZxid(messageMap);
                //获取发运订单列表
                fyddids = wmsSetBoxMapper.getFyddIdsByXbh(xbh);
            }
            //修改发运订单运费
            for (String fyddid : fyddids) {
                WmsShipmentOrder so=new WmsShipmentOrder();
                so.setId(fyddid);
                so.setZyf(wmsBoxMapper.sumYf(fyddid).toString());
                wmsBoxMapper.updateSoYf(so);
            }
            json = JSONObject.fromObject(JSONArray.fromObject(json.get("data").toString()).get(0));
            message = json.get("templateurl").toString();
        }
        return message;
    }

    /**
    * 分页查询
    * @param entity 实体
    * @return Page<WmsReview>
    */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "列表页面查询")
    public Page<Map<String,Object>> baseSelectPage(WmsReview entity ){
        PageHelper.startPage(entity.getPage(),entity.getRows());
        return (Page<Map<String,Object>>)dao.baseSelectPage( entity );
    }

   /**
    * 查询（根据主键ID查询）
    * @param id 主键ID
    * @return WmsReview
    */
    public WmsReview baseSelectByPrimaryKey(String id ){
         return dao.baseSelectByPrimaryKey( id );
    }

   /**
    * 查询（根据ID 批量查询）
    * @param idList 主键ID列表
    * @return list
    */
    public Integer baseSelectBathPrimaryKeys(List<WmsReview> idList ){
         return dao.baseSelectBathPrimaryKeys( idList );
    }

   /**
    *修改 （匹配有值的字段）
    * @param list
    * @return int
    */
   @BaseServiceDescribe(moduleName = "出库复核",btnName = "修改出库复核")
   @Transactional
    public void baseUpdateByPrimaryKeySelective(List<WmsReview> list, HttpSession session) throws SucessException,ServiceException {
       UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
       SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       for (WmsReview entity : list) {
           entity.setClr(userinfo.getUser().getName());
           entity.setClsj(formatter.format(new Date()));
           WmsReview wmsReview =  dao.baseSelectByPrimaryKey(entity.getId());
           WmsSetBox wmsSetBox =  wmsSetBoxMapper.baseSelectByPrimaryXbh(wmsReview.getXbh());
           List<String> ids = null;
           //判断如果是集拼箱 则根据集拼箱ID查询对应的箱IDS 否则直接查询箱IDS
           if(wmsSetBox != null){
               ids =  wmsSetBoxMapper.getWmsBoxIdsByJpxid(wmsSetBox.getId());
           }else{
               ids =   wmsBoxMapper.baseSelectByPrimaryXbh(wmsReview.getXbh());
           }
           Map<String,Object> map = new HashMap<String,Object>();
           map.put("fhzt",entity.getFhzt().toString());
           map.put("list",ids);
           //根据所属装箱ID 修改
           dao.updatePickingFhzt(map);
           dao.baseUpdateByPrimaryKeySelective(entity);
       }
       throw new SucessException("修改出库复核成功");
   }


   /**
    *修改（根据主键ID修改）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKey(WmsReview entity){
         return dao.baseUpdateByPrimaryKey( entity);
    }

    public static void main(String args[]){
        String str = "……";
        System.out.println(str.length());
    }
}
